﻿create procedure dbo.CreateTakeoutProvider
(
		@MenuID int,
		@PaymentSourceID int,
		@UserID int,
		@ExpirationTime datetime ,
		@StartTime datetime ,
		@MaximumOrders int = 15,
		@TakeoutCharge money = 1.00,
		@Instructions varchar(2000) = '',
		@AllowPayMeLater bit = 0,
		@Audiences varchar(2000),
		@PaymentSettings varchar(8000), /* CSV Name Value Collection */
		@PortalID int,
		@TakeoutProviderID int = null OUTPUT
	)
AS
	SET NOCOUNT ON 
		
	DECLARE @Pos int
	
	-- DECLARE @TakeoutProviderID int
	BEGIN TRANSACTION

/* Begin transaction, start with inserting record into takeout provider */

	
INSERT INTO dbo.TakeoutProvider
                      (MenuID, PaymentSourceID, UserID, ExpirationTime, StartTime, MaximumOrders, TakeoutCharge, Instructions, AllowPayMeLater, [SiteID])
VALUES     (@MenuID, @PaymentSourceID, @UserID, @ExpirationTime, @StartTime, @MaximumOrders, @TakeoutCharge, @Instructions, @AllowPayMeLater, 
                      @PortalID)

/* Get the Identity of the TakeoutProvider */

SET @TakeoutProviderID = SCOPE_IDENTITY()

/* Set the Audiences */

DECLARE @AudienceID varchar(10)

SET @Audiences = LTRIM(RTRIM(@Audiences)) + ','
SET @Pos = CHARINDEX(',', @Audiences, 1)

	DECLARE @Name varchar(255)
	DECLARE @Value varchar(2000)
IF REPLACE(@Audiences, ',', '') <> ''
	BEGIN
		WHILE @Pos > 0
		BEGIN
			SET @AudienceID = LTRIM(RTRIM(LEFT(@Audiences, @Pos - 1)))
			IF @AudienceID <> ''
				BEGIN
					INSERT INTO dbo.TakeoutProviderAudiences (AudienceID, TakeoutProviderID) 
						VALUES (CAST(@AudienceID AS int), @TakeoutProviderID) --Use Appropriate conversion
				END
			
			SET @Audiences = RIGHT(@Audiences, LEN(@Audiences) - @Pos)
			SET @Pos = CHARINDEX(',', @Audiences, 1)

		END
	END	
	

/* Set the Payment Settings */

	SET @PaymentSettings = LTRIM(RTRIM(@PaymentSettings))+ ','
	SET @Pos = CHARINDEX(',', @PaymentSettings, 1)


	IF REPLACE(@PaymentSettings, ',', '') <> ''
	BEGIN
		WHILE @Pos > 0
		BEGIN
			
			
			Set @Name = LTRIM(RTRIM(LEFT(@PaymentSettings, @Pos -1)))
			
			SET @PaymentSettings = RIGHT(@PaymentSettings, LEN(@PaymentSettings) - @Pos)
			SET @Pos = CHARINDEX(',', @PaymentSettings, 1)
			
			SET @Value = LTRIM(RTRIM(LEFT(@PaymentSettings, @Pos - 1)))
			
			SET @PaymentSettings = RIGHT(@PaymentSettings, LEN(@PaymentSettings) - @Pos)
			SET @Pos = CHARINDEX(',', @PaymentSettings, 1)

			INSERT INTO dbo.PaymentSettings
			                      (Name, Value, TakeoutProviderID)
					VALUES     (@Name,@Value,@TakeoutProviderID)
		END
	END	

IF @@error = 0
	BEGIN
	
		COMMIT TRANSACTION

	END
ELSE
	BEGIN
		ROLLBACK TRANSACTION
	END

	RETURN


